import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams, Select, ToastController} from 'ionic-angular';
import {ClientRenewalProvider} from "../../../providers/client/client-renewal/client-renewal.provider";
import {CallNumber} from "@ionic-native/call-number";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {InfiniteScrollModel} from "../../../model/common/infinite-scroll.model";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {SideMenuService} from "../../../services/common/side-menu.service";
import {TabsPage} from "../../tabs/tabs";
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {LoadingService} from "../../../services/common/loading.service";

@IonicPage()
@Component({
    selector: 'page-client-renewal',
    templateUrl: 'client-renewal.html',
    providers: [
        CallNumber,
        ClientRenewalProvider,
        ClientNoteEditProvider,
        SideMenuService,
        CallNumberService
    ]
})
export class ClientRenewalPage extends InfiniteScrollModel {
    clientsData;
    dataType;
    //续期日期选项
    itemChangeOption = 60;
    //数据添加方式(0为替换，1为追加)
    addDataWay = 0;
    infiniteScroll = null;
    @ViewChild(Content) content: Content;
    dataTotal:string;
    currentClient;
    currentMobileList;
    currentMobile;
    isLoaded :boolean = false;
    get clientItemHeight():string{
        const windowW = window['innerWidth'];
        return (windowW * 38.34 / 100) + 'px';
    }
    isScrolling = false;
    isViewDidLoad = false;
    isArriveBottom = false;
    renewal="renewal";
    @ViewChild('selectMobile') selectMobile: Select;



    constructor(public navCtrl: NavController,
                public renewalProvider: ClientRenewalProvider,
                public navParams: NavParams,
                private callNumber: CallNumber,
                private clientNoteEditProvider: ClientNoteEditProvider,
                public toastCtrl: ToastController,
                private sideMenuService:SideMenuService,
                public changeRef: ChangeDetectorRef,
                public tabsPage:TabsPage,
                private callNumberService: CallNumberService,
                private load: LoadingService,
                ) {
        super();
    }

    ionViewDidLoad(){
        this.isViewDidLoad = true;
        this.getRenewalListData(60);
    }

    ionViewDidEnter(){
        if(!this.isViewDidLoad){
            //进入本页面时，如果数据有更新(例如删除，修改等)，则需要重新拉取客户列表
            const clientUpdated = MessageBushService.getMessage(MessageBushService.keys.renewalClientListUpdated);
            if(clientUpdated == '1'){
                MessageBushService.setMessage(MessageBushService.keys.renewalClientListUpdated,void 0);
                this.ionViewDidLoad();
            }
        }
        this.isViewDidLoad = false;
    }
    openRoot=(name, index)=>this.openTab(name, index);

    openMenu(myEvent){
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index){
        this.navCtrl.popToRoot()
        this.tabsPage.openPage({name:name, index:index});
    }
    nativeCallPhone(mobilePhone?:string){
        if(mobilePhone) this.currentMobile = mobilePhone;
        // this.callNumber.callNumber(this.currentMobile, true)
        //     .then(() => {
        //         this.clientNoteEditProvider.saveNote({
        //             type: 2,
        //             noteType: 3,
        //             content: "拨打电话",
        //             contentType: 1,
        //             clientNumber: this.currentClient.clientId
        //         }).subscribe(() => {
        //         }, error => {
        //             console.log('记录日志失败');
        //         });
        //     })
        //     .catch(() => console.log('没打通'));
        console.log(this.currentMobile);
        this.callNumberService.makeCall(this.currentMobile,
            this.callNumberService.initClientNoteLog(this.currentClient.clientId),
            true,
            this.callNumberService.initFollowStateLog(this.currentClient.clientId));
    }

    goUp() {
        if(this.isScrolling){
            setTimeout(() => {
                this.goUp();
            },300);
            return;
        }
        this.content.scrollToTop();
    }
    scrollStart(e){
        this.isScrolling = true;
    }
    scrollEnd(e){
        this.isScrolling = false;
    }

    scrolling(){
        const dimensions = this.content.getContentDimensions();
        if((!this.clientsData || this.clientsData.length==0) && this.isLoaded){
            return;
        }
        const temp1=dimensions.scrollHeight-dimensions.scrollTop-dimensions.contentHeight<100;
        if (temp1 !== this.isArriveBottom) {
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }
    }

    backHandle() {
        this.navCtrl.pop();
    }

    itemChangeHandle(e) {
        this.pageParams.pageNum = 1;
        if(this.infiniteScroll)this.infiniteScroll.enable(true);
        this.addDataWay = 0;
        this.itemChangeOption = e.v;
        this.getRenewalListData(e.v,0,() => {
            this.goUp();
        });
    }

    /**
     * 获取续期客户列表数据
     * @param {number} type
     * @param {number} notLoading
     * @param {any} cb
     */
    getRenewalListData(type: number = 60, notLoading = 0, cb = null) {
        this.isArriveBottom = false;
        this.isLoaded = false;
        this.dataType = type;
        this.pageParams.pageNum = 1;
        this.pageParams.pageSize = 0;
        if (notLoading !== 1) {
            this.load.showLoading();
        }
        this.renewalProvider.getRenewalList(type, 0,this.pageParams,1).subscribe(res => {
            if(!res || !res.total)return;
            this.pageParams.pageNum = 1;
            this.pageParams.pageSize = res.total;
            this.renewalProvider.getRenewalList(type, 1,this.pageParams).subscribe(res => {
                this.pageInfo = res;
                this.isLoaded = true;
                if(!res.list || !res.list.length){
                    this.dataTotal = '(0)';
                }else{
                    this.dataTotal = `(${this.pageInfo.total})`;
                }
                const list = this.pageInfo.list;
                list.forEach(client => {
                    if(client.passedInfo){
                        client.dateDescribe = {
                            level: 'urgent',  //'urgent'、'defer'、'normal'
                            value:window['unescape'](client.passedInfo.replace(/\\u/g, '%u'))
                        };
                    }
                });
                if(this.addDataWay === 0){
                    this.clientsData = list;
                }else{
                    this.clientsData = this.clientsData.concat(list);
                }
                // this.clientsData = this.clientsData.filter(client => client.mobilePhone.length > 1);
                //过滤为空的电话号码
                this.clientsData = this.renewalProvider.checkMobileNull(this.clientsData);
                if (cb) cb();
                this.load.dismissLoading();
            }, (code) => {
                if (cb) cb();
                this.load.dismissLoading();
            });
        },error=>{
            if (cb) cb();
            this.load.dismissLoading();
        });
    }

    /**
     *  toast 提示信息
     * @param {string} message 提示内容
     * @param {string} position 显示位置
     */
    toast(message: string, position: string) {
        this.toastCtrl.create({
            message: message,
            position: 'middle',
            duration: 1200
        }).present();
    }

    /**
     * 跳转到续期详情
     */
    viewDetail(ev,item){
        ev.stopPropagation();
        this.navCtrl.push('ClientRenwalDetailPage',{"id":item.clientId,"days":this.itemChangeOption})
    }
    /**
     * 打电话
     */
    callClickHandle(item) {
        this.currentClient = item;
        this.currentMobileList = item.mobilePhone;
        if(!this.currentMobileList || this.currentMobileList.length < 1)return;
        if(this.currentMobileList.length === 1 && this.currentMobileList[0].mobile){
            this.currentMobile = this.currentMobileList[0].mobile;
            this.nativeCallPhone();
            return;
        }
        setTimeout(() => {
            this.selectMobile.open();
        });
    }

    /**
     * 到客户详情
     * @param clientNum
     */
    goToDetail(clientNum) {
        this.navCtrl.push('HolderClientDetailPage', {
            clientNum: clientNum
        })
    }

    getMore(infiniteScroll){
        this.infiniteScroll = infiniteScroll;
        const totalPage = Math.ceil(this.pageInfo.total / this.pageInfo.pageSize);
        if(this.pageParams.pageNum < totalPage){
            this.pageParams.pageNum++;
            this.addDataWay = 1;
            this.getRenewalListData(this.itemChangeOption,1,() => {
                infiniteScroll.complete();
            });
        }else{
            this.isArriveBottom = true;
            infiniteScroll.complete();
        }
    }


    /**
     * 下拉刷新
     * @param refresher
     */
    doRefresh(refresher) {
        this.getRenewalListData(this.dataType, 1, () => {
            refresher.complete();
        });
    }

}
